package com.cloud.seckill.schedule;

import com.cloud.seckill.service.SeckillService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author lisw
 * @create 2021/8/22 17:19
 * 秒杀商品的定时上架：
 * 每天晚上3点。上架最近3天的参与秒杀的产品。这样可以做一个秒杀的预告
 */
@Slf4j
@Service
public class SeckillSkuService {

    private final String upload_lock = "seckill:upload:lock";
    @Resource
    SeckillService seckillService;
    @Resource
    RedissonClient redissonClient;

    @Scheduled(cron = "*/3 * * * * ?")
    public void uploadSeckillSkuLatest3Days() {
        // 1、重复上架无需处理。
        log.info("上架秒杀商品信息...");
        RLock lock = redissonClient.getLock(upload_lock);
        lock.lock(10, TimeUnit.MINUTES);
        try {
            seckillService.uploadSeckillSkuLatest3Days();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            lock.unlock();
        }


    }
}
